import lombok.extern.slf4j.Slf4j;

/**
 * wait和notifyAll的使用
 * 以及 while(条件不成立)时持续wait
 */
@Slf4j
public class TestWaitAndNotifyAll {

    static final Object room = new Object();
    static boolean hasCigarette = false;
    static boolean hasTakeout = false;

    public static void main(String[] args) {
        new Thread(() -> {
            synchronized (room) {
                log.info("有烟没?[{}]", hasCigarette);
                while (!hasCigarette) {
                    log.info("没烟，先歇会！");
                    try {
                        room.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                log.info("有烟没?[{}]", hasCigarette);
                if (hasCigarette) {
                    log.info("可以开始干活了");
                } else {
                    log.info("没干成活！");
                }
            }
        }, "小南").start();

        new Thread(() -> {
            synchronized (room) {
                log.info("外卖有没?[{}]", hasTakeout);
                while (!hasTakeout) {
                    log.info("没外卖，先歇会！");
                    try {
                        room.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                log.info("外卖有没?[{}]", hasTakeout);
                if (hasTakeout) {
                    log.info("可以开始干活了");
                } else {
                    log.info("没干成活！");
                }
            }
        }, "小女").start();

        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        new Thread(() -> {
            synchronized (room) {
                log.info("送外卖的 come in...");
                hasTakeout = true;
                room.notifyAll();
            }
        }, "送外卖的").start();
    }

}
